# Recursively delete all target folders script
Write-Host "========================================" -ForegroundColor Cyan
Write-Host "Recursively delete all target folders script" -ForegroundColor Cyan
Write-Host "========================================" -ForegroundColor Cyan
Write-Host ""

# Confirm operation
$confirm = Read-Host "Confirm to delete all target folders? (y/n)"
if ($confirm -ne 'y') {
    Write-Host "Operation cancelled" -ForegroundColor Yellow
    exit
}

# Scan and delete target folders
Write-Host "Start scanning and deleting target folders..." -ForegroundColor Green
$targetFolders = Get-ChildItem -Path . -Recurse -Directory -Name "target" -ErrorAction SilentlyContinue

if ($targetFolders.Count -eq 0) {
    Write-Host "No target folders found" -ForegroundColor Yellow
    exit
}

Write-Host "Found $($targetFolders.Count) target folders:" -ForegroundColor Green

$deletedCount = 0
foreach ($folder in $targetFolders) {
    $fullPath = Join-Path $PWD $folder
    try {
        Remove-Item -Path $fullPath -Recurse -Force -ErrorAction Stop
        Write-Host "  ✓ Deleted: $folder" -ForegroundColor Green
        $deletedCount++
    }
    catch {
        Write-Host "  ✗ Delete failed: $folder ($_)" -ForegroundColor Red
    }
}

Write-Host ""
Write-Host "========================================" -ForegroundColor Cyan
Write-Host "Delete completed! Total deleted: $deletedCount target folders" -ForegroundColor Cyan
Write-Host "========================================" -ForegroundColor Cyan

# Process Git repositories
Write-Host ""
Write-Host "Processing target folders in Git repositories..." -ForegroundColor Green

$gitRepos = Get-ChildItem -Directory | Where-Object { Test-Path "$_\.git" }

foreach ($repo in $gitRepos) {
    Write-Host "Processing repository: $($repo.Name)" -ForegroundColor Yellow
    Push-Location $repo.FullName
    
    # Remove target from Git index
    $gitResult = git rm -r --cached target/ 2>$null
    if ($LASTEXITCODE -eq 0) {
        Write-Host "  ✓ Removed target from Git index" -ForegroundColor Green
    }
    
    Pop-Location
}

Write-Host ""
Write-Host "All operations completed!" -ForegroundColor Cyan
Read-Host "Press Enter to exit"